package com.woniuxy.java106crm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.java106crm.entity.Customer;
import com.woniuxy.java106crm.entity.Lost;
import com.woniuxy.java106crm.entity.Measure;
import com.woniuxy.java106crm.mapper.LostMapper;
import com.woniuxy.java106crm.request.ResPage;
import com.woniuxy.java106crm.service.CustomerService;
import com.woniuxy.java106crm.service.LostService;
import com.woniuxy.java106crm.service.MeasureService;
import com.woniuxy.java106crm.service.SureLostService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class LostServiceImpl implements LostService {

    @Resource
    private LostMapper lostMapper;

    @Resource
    private MeasureService measureService;

    @Resource
    private SureLostService sureLostService;

    @Resource
    private CustomerService customerService;

    @Override
    public List<Lost> findAll() {
        return lostMapper.findAll();
    }

    @Override
    public List<Lost> findAllLost() {
        return lostMapper.findAllLost();
    }

    @Override
    public void addLost(Lost lost) {
        lostMapper.addLost(lost);
    }

    @Override
    public ResPage<List<Lost>> findAllLostPage(Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<Lost> lostList = lostMapper.findAllLost();
        PageInfo<Lost> info = new PageInfo<>(lostList);
        ResPage<List<Lost>> resPage = new ResPage<>();
        resPage.setSize(size);
        resPage.setCurPage(page);
        resPage.setTotal(info.getTotal());
        resPage.setData(lostList);
        return resPage;
    }

    @Override
    public ResPage<List<Lost>> queryCondition(Integer page, Integer size, Lost lost) {
        PageHelper.startPage(page, size);
        List<Lost> lostList = lostMapper.queryCondition(lost);
        PageInfo<Lost> info = new PageInfo<>(lostList);
        ResPage<List<Lost>> resPage = new ResPage<>();
        resPage.setSize(size);
        resPage.setCurPage(page);
        resPage.setTotal(info.getTotal());
        resPage.setData(lostList);
        return resPage;
    }

    @Override
    public void slow(Lost lost) {
        lostMapper.updateLost(lost);
        Measure measure = new Measure();
        measure.setCid(lost.getId());
        measure.setMeasure(lost.getMeasure());
        measure.setTime(LocalDateTime.now());
        measureService.addMeasure(measure);
    }

    @Transactional
    @Override
    public boolean sure(Lost lost) {
        //将客户表状态改为已流失
        customerService.updateStatusById(lost.getId());
        //在确认流失表插入一条信息
        sureLostService.addSureLost(lost);
        //在将客户表lost信息更新
        return lostMapper.sureLost(lost);
    }
}
